<template>
	<view class="wanlfind-add-container">
		<NavTitle titleKey="commonTitle.申请入驻" />
		<view class="edgeInsetTop"></view>
		<view class="wanlfind-add-container__main">
			<view class="want">
				<view class="padding-bj flex justify-between align-center">
					<view class="text-30">{{$t('pages.user.request.上传资料')}}</view>
				</view>
				<view class="grid col-4 grid-square flex-sub padding-lr-bj">
					<view
						v-if="params.images.length > 0"
						v-for="(item, index) in params.images"
						:key="index"
					>
						<view class="item" @tap="handlePreview(index)">
							<image :src="$wanlshop.oss(item, 100, 100)" mode="widthFix"></image>
						</view>
						<view class="tag" @tap="handleDelImage(index)">
							<text class="wlIcon-31guanbi text-white"></text>
						</view>
					</view>
					<view v-if="params.images.length < 9" @tap="handleImage()">
						<view class="item">
							<view class="text-lg text-gray">
								<text class="wlIcon-tianjia"></text>
								<view v-if="params.images.length === 0" class="margin-top-xs text-sm">{{$t('pages.user.request.添加图片')}}</view>
								<view v-else class="margin-top-xs text-sm">{{$t('pages.user.request.继续添加')}}</view>
							</view>
						</view>
					</view>
			</view>				
				<view class="padding-bj">
								<!-- 入驻类型选择 -->
						<view v-if="userInfo.needSettleType" class="padding-bj">
							<view class="text-30">{{$t('pages.user.request.入驻类型')}}</view>
							<radio-group @change="handleSettleTypeChange">
								<label class="flex align-center margin-top-sm">
									<radio :value="$t('pages.user.request.企业')" :checked="settleType === $t('pages.user.request.企业')" />
									<text class="margin-left-sm">{{$t('pages.user.request.企业')}}</text>
								</label>
								<label class="flex align-center margin-top-sm">
									<radio :value="$t('pages.user.request.个人')" :checked="settleType === $t('pages.user.request.个人')" />
									<text class="margin-left-sm">{{$t('pages.user.request.个人')}}</text>
								</label>
							</radio-group>
						</view>
						<!-- 企业信息 -->
						<view v-if="settleType === $t('pages.user.request.企业')">
							<view class="padding-bj">
								<view class="text-30">{{$t('pages.user.request.上传执照身份证')}}</view>
							</view>
						</view>
						<!-- 个人信息 -->
						<view v-if="settleType === $t('pages.user.request.个人')">
							<view class="padding-bj" v-if="this.params.id == 3">
								<view class="text-30">{{$t('pages.user.request.身份证')}}</view>
							</view>
							<view class="padding-bj" v-else>
								<view class="text-30">{{$t('pages.user.request.身份证货架')}}</view>
							</view>
						</view>
				</view>
				
				<!--翻译上传头像-->
				<view class="want" v-if="this.params.id == 3">
					  <view class="padding-bj flex justify-between align-center">
						<view class="text-30">{{$t('pages.user.request.上传头像')}}</view>
					  </view>
					  <view class="grid col-4 grid-square flex-sub padding-lr-bj">
						<!-- 显示已上传的头像 -->
						<view v-if="params.avatar">
						  <view class="item" @tap="handlePreviewAvatar">
							<image :src="$wanlshop.oss(params.avatar, 100, 100)" mode="widthFix"></image>
						  </view>
						  <view class="tag" @tap="handleDelAvatar">
							<text class="wlIcon-31guanbi text-white"></text>
						  </view>
						</view>
						<!-- 上传按钮 -->
						<view v-if="!params.avatar" @tap="handleAvatar">
						  <view class="item">
							<view class="text-lg text-gray">
							  <text class="wlIcon-tianjia"></text>
							  <view class="margin-top-xs text-sm">{{$t('pages.user.request.添加图片')}}</view>
							</view>
						  </view>
						</view>
					  </view>
				</view>
				
				<view class="padding-bj" v-if="settleType === $t('pages.user.request.企业')" v-show="false">
					<view class="text-30">{{$t('pages.user.request.对公账户')}}</view>
					
					<input
						v-model="params.public_account"
						:placeholder="$t('pages.user.request.请输入对公账户')"
						class="input bg-gray padding-lr-bj radius-bock margin-top-sm"
					/>
				</view>
				
				<view class="padding-bj" v-show="false">
					<view class="text-30">{{$t('pages.user.request.开户行')}}</view>
					
					<input
						v-model="params.bank_name"
						:placeholder="$t('pages.user.request.请输入开户行')"
						class="input bg-gray padding-lr-bj radius-bock margin-top-sm"
					/>
				</view>
				<view class="padding-bj" v-show="false">
					<view class="text-30">{{$t('pages.user.request.银行卡号')}}</view>
					<input
						v-model="params.card_number"
						:placeholder="$t('pages.user.request.请输入') + $t('pages.user.request.银行卡号')"
						class="input bg-gray padding-lr-bj radius-bock margin-top-sm"
					/>
				</view>
				<!-- 用户名输入框 -->
				<view v-if="userInfo.needUsername" class="padding-bj">
					<view class="text-30">{{$t('pages.user.request.姓名')}}</view>
					<input
						v-model="params.username"
						:placeholder="$t('pages.user.request.请输入') + $t('pages.user.request.姓名')"
						class="input bg-gray padding-lr-bj radius-bock margin-top-sm"
					/>
				</view>
				<!-- 手机号输入框 -->
				<view v-if="userInfo.needPhone" class="padding-bj">
					<view class="text-30">{{$t('pages.user.request.联系方式')}}</view>
					<input
						v-model="params.phone"
						:placeholder="$t('pages.user.request.请输入') + $t('pages.user.request.联系方式')"
						class="input bg-gray padding-lr-bj radius-bock margin-top-sm"
					/>
				</view>
				
				<!-- 手机号输入框 -->
				<view v-if="userInfo.needEmail" class="padding-bj">
					<view class="text-30">{{$t('pages.user.request.邮箱')}}</view>
					<input
						v-model="params.email"
						:placeholder="$t('pages.user.request.请输入') + $t('pages.user.request.邮箱')"
						class="input bg-gray padding-lr-bj radius-bock margin-top-sm"
					/>
				</view>
				
				<view v-if="this.params.id == 3" class="padding-bj">
					<view class="text-30">{{$t('pages.user.request.微信号')}}</view>
					<input
						v-model="params.wx"
						:placeholder="$t('pages.user.request.请输入') + $t('pages.user.request.微信号')"
						class="input bg-gray padding-lr-bj radius-bock margin-top-sm"
					/>
				</view>
				
				<!-- 种草内容 -->
				
				<view class="padding-bj flex justify-between align-center" v-if="userInfo.needContent">
					<view class="text-30">
						<text class="wlIcon-xiugaioryijian margin-right-xs text-bold"></text>
						{{$t('pages.user.request.简介')}}
					</view>
				</view>
				<view class="padding-bj bg-gray margin-lr-bj radius-bock" v-if="userInfo.needContent">
					<editor
						id="editor"
						v-model="params.content"
						@ready="onEditorReady"
						@input="onEditorInput"
						:placeholder="$t('pages.user.request.请输入')  + $t('pages.user.request.简介')"
					/>
				</view>
			</view>
			
			<checkbox-group :class="checked == 1 ? 'shake-horizontal' : ''" class="auth-clause" @change="CheckboxChange">
				<checkbox class="orange" :class="checked == 2 ? 'checked' : ''" :checked="checked == 2 ? true : false" value="2" />
				<view>
					{{$t('pages.user.request.我已阅读')}}<text @tap="onDetails(params.id, $t('pages.user.request.入驻协议'))">{{$t('pages.user.request.入驻协议')}}</text>
				</view>
			</checkbox-group>
		</view>
		<!-- 底部 -->
		<view class="safeAreaBottom"></view>
		<view class="wanlfind-add-container__foot">
			<view class="cu-bar tabbar foot flex flex-direction">
				<button class="cu-btn bg-red lg" @tap="handleSubmit">
					<text class="wlIcon-fabu margin-right-sm"></text>
					
					{{$t('pages.user.request.申请入驻')}}
				</button>
			</view>
		</view>
		</view>
</template>

<script>
export default {
	data() {
		return {
			modalName: null,
			orderList: [],
			current_page: 1, //当前页码
			last_page: 1, //总页码
			status: 'loading',
			contentText: {
				contentdown: this.$t('message.下拉加载更多'),
				contentrefresh: this.$t('message.加载中'),
				contentnomore: ''
			},
			chooseList: [],
			video:{
				tempFilePath: null, // 本地缓存
				progress: 0, //上传进度
				totalBytesSent: 0, //已经上传的数据长度
				totalBytesExpectedToSend: 0, //预期需要上传的数据总长度
			},
			params: {
				type: null,
				content: '',
				images: [],
				username: '',
				phone: '',
				card_number:'',
				bank_name:'',
				email:'',
				wx:'',
				avatar:''
			},
			requiredData: [], // 存储 required_data 字段的值
			settleType: '', // 用户选择的入驻类型（'企业' 或 '个人'）
			fee_switch:0,
			userInfo: {
							needUsername: true,
							needPhone: true,
							needBankName:false,
							needCardNumber:false,
							needBankName:false,
							needEmail:false,
							needContent:false,
							needSettleType: false // 是否需要选择入驻类型
						},
						checked: 0
		};
	},
	onLoad(option) {
		// this.params.type = option.type;
		this.params.id = option.id;
		this.getArrivalInfo();
	},
	methods: {
		CheckboxChange(e) {
			this.checked = e.detail.value;
		},
		handleSettleTypeChange(e) {
				this.settleType = e.detail.value;
				if(e.detail.value == this.$t('pages.user.request.企业')){
					this.params.type = 1;
				}else{
					this.params.type = 2;
				}
			},		
		async getArrivalInfo() {
				try {
					
					
					await uni.request({
						url: '/wanlshop/Arrival/arrivalInfo',
						method: 'GET',
						data: {
							id: this.params.id
						},
						success: res => {
							// 更新 userInfo
							this.requiredData = res.data.required_data ? res.data.required_data.split(',') : [];
							// 根据 requiredData 更新 userInfo
							this.userInfo.needPhone = this.requiredData.includes('2');
							this.userInfo.needEmail = this.requiredData.includes('3');
							this.userInfo.needContent = this.requiredData.includes('4');
							this.fee_switch = res.data.fee_switch;
							// 更新 typeData
							this.typeData = res.data.type_data || '';
							// 如果 typeData 包含英文逗号，则需要选择入驻类型
							if (this.typeData.includes(',')) {
								this.userInfo.needSettleType = true;
							} else {
								// 如果没有小数点，直接设置 settleType
								if (this.typeData === '1') {
									this.settleType = this.$t('pages.user.request.企业');
									this.params.type = 1;
								} else if (this.typeData === '2') {
									this.settleType = this.$t('pages.user.request.个人');
									this.params.type = 2;
								}
							}
						}
					});
				} catch (error) {
					this.$wanlshop.msg('网络错误，请重试');
				}
			},
		
		// 发布
		async handleSubmit() {
			if(this.checked == 0){
				this.$wanlshop.msg(this.$t('pages.user.request.请先勾选入驻协议'));
				return;
			}
			const params = this.params;
			// 校验入驻类型
			if (this.userInfo.needSettleType && !this.settleType) {
				this.$wanlshop.msg(this.$t('pages.user.request.请选择入驻类型'));
				return;
			}
			// 校验对公账户（企业类型）
			// if (this.settleType === this.$t('pages.user.request.企业') && !this.params.public_account) {
			// 	this.$wanlshop.msg(this.$t('pages.user.request.请输入对公账户'));
			// 	return;
			// }
			if(this.fee_switch == 1){
				await uni.request({
					url: '/wanlshop/Arrival/orderAdd',
					method: 'POST',
					data: params,
					success: res => {
						// this.$wanlshop.to(res.data.data.web_url);
						window.location.href = res.data.data.web_url;
					}
				});
			}else{
				await uni.request({
					url: '/wanlshop/Arrival/addData',
					method: 'POST',
					data: params,
					success: res => {
						this.$wanlshop.msg(this.$t('pages.user.request.申请成功'));
						this.$wanlshop.to('/pages/page/success?type=arrival');
					}
				});
			}
		},
	
		handleImage() {
			uni.chooseImage({
				crop: {
					quality: 60
				},
				success: res => {
					uni.request({
						url: '/wanlshop/common/uploadData',
						success: updata => {
							for (let i = 0; i < res.tempFilePaths.length; i++) {
								// 读取图片宽高
								uni.getImageInfo({
									src: res.tempFilePaths[i],
									success: image => {
										uni.uploadFile({
											url: updata.data.uploadurl,
											filePath: image.path,
											name: 'file',
											formData:updata.data.storage == 'local' ? null : updata.data.multipart,
											success: data => {
												this.params.images.push(JSON.parse(data.data).data.url);
											},
											fail: error =>{
												uni.showToast({title: JSON.parse(error.data).msg, icon: 'error', position: true});
											}
										});
									}
								});
							}
						}
					});
				}
			});
		},
		handlePreview(index) {
			let imgArr = [];
			for (let item of this.params.images) {
				imgArr = imgArr.concat(this.$wanlshop.oss(item, 500));
			}
			uni.previewImage({
				urls: imgArr,
				current: imgArr[index],
				indicator: 'number'
			});
		},
		handleDelImage(index) {
			this.params.images.splice(index, 1);
		},


			
		// 选择并上传头像
		  handleAvatar() {
		    uni.chooseImage({
		      count: 1, // 限制为单张图片
		      crop: { quality: 60 },
		      success: res => {
		        const tempFilePath = res.tempFilePaths[0];
		        uni.request({
		          url: '/wanlshop/common/uploadData',
		          success: updata => {
		            uni.getImageInfo({
		              src: tempFilePath,
		              success: image => {
		                uni.uploadFile({
		                  url: updata.data.uploadurl,
		                  filePath: image.path,
		                  name: 'file',
		                  formData: updata.data.storage == 'local' ? null : updata.data.multipart,
		                  success: data => {
		                    // 将上传结果单独赋值给avatar字段
		                    const response = JSON.parse(data.data);
		                    this.params.avatar = response.data.url;
		                  },
		                  fail: error => {
		                    uni.showToast({title: JSON.parse(error.data).msg, icon: 'error'});
		                  }
		                });
		              }
		            });
		          }
		        });
		      }
		    });
		  },
		  
		  // 删除头像
		  handleDelAvatar() {
		    this.params.avatar = '';
		  },
		  
		  // 预览头像
		  handlePreviewAvatar() {
		    if (this.params.avatar) {
		      uni.previewImage({
		        urls: [this.$wanlshop.oss(this.params.avatar, 500)],
		        current: 0
		      });
		    }
		  },
		
		
		handleUpper() {
			if (this.last_page === this.current_page) {
				this.status = 'noMore';
			} else {
				this.status = 'loading';
				this.current_page++;
				this.handleGoods('upper');
			}
		},
		handleGoods(type) {
			this.modalName = 'goods';
			if (this.orderList.length > 0 && type !== 'upper') {
				return;
			}
			uni.request({
				url: '/wanlshop/order/getBuyList',
				data: {
					page: this.current_page
				},
				success: res => {
					this.last_page = res.data.last_page; // 总页码
					this.current_page = res.data.current_page; // 当前页面
					if (res.data.last_page === res.data.current_page) {
						this.status = 'noMore';
					} else {
						this.status = 'more';
					}
					if (res.data.total === 0) {
						this.status = 'noMore';
					}
					this.orderList = type === 'upper' ? this.orderList.concat(res.data.data) : res.data.data;
				}
			});
		},
		handleHideModal() {
			this.modalName = null;
		},
		handleChoose(index) {
			if (this.chooseList.length >= 8) {
				this.$wanlshop.msg('最多选择 8 个商品');
			} else {
				let goods = this.orderList[index];
				if (!goods.choose) {
					this.$set(goods, 'choose', true);
				} else {
					goods.choose = false;
				}
				this.formatGoods();
			}
		},
		formatGoods() {
			var list = [];
			var ids = [];
			this.orderList.map(item => {
				if (item.choose) {
					list.push(item);
					ids.push(item.id);
				}
			});
			this.chooseList = list;
			this.params.goods_ids = ids;
		},
		onEditorInput(e) {
			this.params.content = e.detail.html;
		},
		onEditorReady() {
			// #ifdef MP-BAIDU
			this.editorCtx = requireDynamicLib('editorLib').createEditorContext('editorId');
			// #endif

			// #ifdef APP-PLUS || H5 ||MP-WEIXIN
			uni.createSelectorQuery()
				.select('#editor')
				.context(res => {
					this.editorCtx = res.context;
				})
				.exec();
			// #endif
		}
	}
};
</script>

<style lang="scss">
	.input {
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
	}
.wanlfind-add-container {
	&__main {
		.video {
			.upload {
				position: relative;
				width: 220rpx;
				height: 300rpx;
				video{
					width: 220rpx;
					height: 300rpx;
				}
				.loading{
					position: absolute;
					top: 0;
					bottom: 0;
					right: 0;
					left: 0;
				}
			}
			#editor {
				flex: 1;
				height: 240rpx;
				min-height: 100rpx;
			}
		}
		.grid {
			position: relative;
			.item {
				position: absolute;
				top: 0;
				bottom: 0;
				left: 0;
				right: 0;
				z-index: 1;
				display: flex;
				justify-content: center;
				align-items: center;
				text-align: center;
				border-radius: 18rpx;
				overflow: hidden;
				background-color: #f0f0f0;
			}
			.tag {
				position: absolute;
				top: 0rpx;
				right: 0rpx;
				z-index: 3;
				width: 40rpx;
				height: 40rpx;
				border-radius: 5500rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				text-align: center;
				overflow: hidden;
				background-color: #e6162c;
			}
		}
	}
	&__foot {
		.tabbar {
			z-index: 10;
			background-color: transparent;
			.cu-btn {
				width: calc(100% - 50rpx);
				font-size: 32rpx;
				height: 86rpx;
			}
		}
	}
	&__modal {
		.scroll-y {
			padding-bottom: 0;
			.item {
				display: flex;
				image {
					width: 120rpx;
					height: 120rpx;
					flex-shrink: 1;
				}
				.details {
					& > view {
						width: 100%;
					}
					flex: 1;
					display: flex;
					flex-wrap: wrap;
					align-content: space-between;
				}
			}
		}
	}
}
</style>
